﻿using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DevelopersToolbox.Util {
    public class KeyboardInfo {
        [DllImport("user32")]
        private static extern short GetKeyState(int vKey);

        private KeyboardInfo() {

        }

        public static KeyStateInfo GetKeyState(Keys key) {
            short keyState = GetKeyState((int)key);
            int low = Low(keyState);
            int high = High(keyState);
            bool toggled = low == 1 ? true : false;
            bool pressed = high == 1;
            return new KeyStateInfo(key, pressed, toggled);
        }

        private static int High(int keyState) {
            return keyState > 0 ? keyState >> 0x10 : (keyState >> 0x10) & 0x1;
        }

        private static int Low(int keyState) {
            return keyState & 0xffff;
        }
    }

}
